#include "timeitem.h"
#include <QTimer>
#include <QPainter>

TimeItem::TimeItem()
{
    m_time = new QTimer(this);
    m_time->setInterval(1000);
    connect(m_time,SIGNAL(timeout()),this,SLOT(updateTime()));

    m_strtime = QString("00:00");
}

void TimeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QFont f("Times [Cronyx]",5);//"Times [Cronyx]", "Palatino". "Helvetica [Cronyx]".
    painter->setFont(f);

    painter->drawText(QRectF(0.0f,0.0f,120.0f,20.0f),
                      Qt::AlignCenter,
                      QString(tr("game time")));
    painter->drawText(QRectF(0.0f,20.0f,120.0f,20.0f),
                      Qt::AlignCenter,
                      m_strtime);
}

QRectF TimeItem::boundingRect() const
{
    return QRectF(0.0f,0.0f,120.0f,40.0f);
}

void TimeItem::updateTime()
{
    if(++m_mmt.isecond > 59)
    {
        m_mmt.isecond = 0;
        if(++m_mmt.iminute > 59)
        {
            m_mmt.iminute = 0;
            ++m_mmt.ihour;
        }
    }

    if(m_mmt.ihour > 0)
    {
        m_strtime = QString("%1:%2%3:%4%5").arg(m_mmt.ihour)
                .arg(static_cast<int>(m_mmt.iminute / 10)).arg(m_mmt.iminute % 10)
                .arg(static_cast<int>(m_mmt.isecond / 10)).arg(m_mmt.isecond % 10);
    }
    else
    {
        m_strtime = QString("%1%2:%3%4")
                .arg(static_cast<int>(m_mmt.iminute / 10)).arg(m_mmt.iminute % 10)
                .arg(static_cast<int>(m_mmt.isecond / 10)).arg(m_mmt.isecond % 10);
    }
}

void TimeItem::beginTime(bool bcontinue)
{
    if(bcontinue)
    {
        updateTime();
    }
    else
    {
        m_mmt.ihour = 0;
        m_mmt.iminute = 0;
        m_mmt.isecond = 0;
        m_strtime = QString("00:00");
    }

    m_time->start();
}
